package sqls

import (
	"strings"
	"errors"
	"fmt"
	log "code.google.com/p/log4go"
	"EasyData/global"
)

const(
	invaildCharacterOne = "--"
	invaildCharacterTwo = "/"
	invaildCharacterThree ="*"
	invaildCharacterFour =";"

	requiredCharacterOne="?"
)
/**
	解析sql语句，过滤不合格的sql语句
	包括，
	1,condition中没有参数，即没有?号，没有?号的sql语句表示没有参数，有可能把全库删掉
    2,特殊字符，包含 -- 包含 / * ; 等字符
	以上字符的sql语句不予通过
 */
func ParseSql() error {

	count :=0
	tasks := global.Config().Tasks
	/**
		必须字符过滤
	 */
	var requiredCharacters = []string{requiredCharacterOne}
	/**
		无效字符过滤
	 */
	var invalidCharacters = []string{invaildCharacterOne,invaildCharacterTwo,invaildCharacterThree,invaildCharacterFour}
	for index := range tasks {
		task := tasks[index]
		if task.IsUse {
			count ++
			for i := range requiredCharacters {
				if !strings.Contains(task.Condition, requiredCharacters[i]) {
					errstr := fmt.Sprintf(
						"task name [%s] database [%s] condition [%s] contions no required character [%s]",
						task.TaskName, task.Database, task.Condition, requiredCharacters[i])
					log.Error(errstr)
					return errors.New(errstr)
				}
			}
			for j := range invalidCharacters {
				if strings.Contains(task.Condition, invalidCharacters[j]) {
					errstr := fmt.Sprintf(
						"task name [%s] database [%s] condition [%s] contions invail character [%s]",
						task.TaskName, task.Database, task.Condition, invalidCharacters[j])
					log.Error(errstr)
					return errors.New(errstr)
				}
			}
		}
	}
	if count==0 {
		return errors.New("tasks[inUse:true] must not be empty ")
	}
	return nil
}